package com.nus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nus.database.DBAdaptor;
import com.nus.parsers.ParserAPIs;
import com.nus.representations.IvleNews;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SportsFinalActivity extends Activity {
	Toast mToast;
	protected static int HELLO_ID = 1;
	  private static final int REQUEST_CODE = 1234;
	public ImageButton home;
    public Calendar cal;
    public String value;
	protected TextView title;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.sportsfinallayout);
		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
		 title = (TextView) findViewById(R.id.titleheader);
		 title.setText("Sports Booking");
		 ImageView b = (ImageView)findViewById(R.id.home);
		  b.setImageDrawable(getResources().getDrawable(R.drawable.sports));
		//home = (ImageButton) findViewById(R.id.home);
		/*home.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.nus.OptionsActivity"));
			}
		});*/
		boolean netconn = checkInternetConnection();
		if (!netconn) {
			Toast.makeText(getApplicationContext(),
					"Please check your internet or 3G connection",
					Toast.LENGTH_LONG).show();
		}
		Button remind = (Button) findViewById(R.id.remind);
		remind.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			cal = Calendar.getInstance(); // for using this you
														// need to import
														// java.util.Calendar;
				StringTokenizer st = new StringTokenizer(SportsActivity.rd
						.getTime(), ":");
				int hours = Integer.parseInt(st.nextToken());
				int mins = Integer.parseInt(st.nextToken());
				Log.i("hour", hours + "");
				Log.i("min", mins + "");
				// add minutes to the calendar object
				cal.set(Calendar.MONTH, SportsActivity.rd.getMonth());
				cal.set(Calendar.YEAR, SportsActivity.rd.getYear());
				cal.set(Calendar.DAY_OF_MONTH, SportsActivity.rd.getDay());
				cal.set(Calendar.HOUR_OF_DAY, hours);
				cal.set(Calendar.MINUTE, mins);
				startVoiceRecognitionActivity();
				// cal.set will set the alarm to trigger exactly at: 21:43, 5
				// May 2011
				// if youe want to trigger the alarm after let's say 5 minutes
				// after is activated you need to put
				//EditText time_rem = (EditText) findViewById(R.id.rem_time);
				
			}
		});

	}

	 private void startVoiceRecognitionActivity()
	    {
	        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
	        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
	                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
	        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "NdroidUS Reminder");
	        startActivityForResult(intent, REQUEST_CODE);
	    }
	 protected void onActivityResult(int requestCode, int resultCode, Intent data)
	    {
		
	        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
	        {
	            // Populate the wordsList with the String values the recognition engine thought it heard
	           final ArrayList<String> matches = data.getStringArrayListExtra(
	                    RecognizerIntent.EXTRA_RESULTS);
	            
	            AlertDialog.Builder builder = new AlertDialog.Builder(this);
	            builder.setMessage("Did you mean this  "+"\""+matches.get(0)+"\"")
	            .setCancelable(false)
	            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int id) {
//	                     MyActivity.this.finish();
	                	Matcher m=null;
	                	Pattern p = Pattern.compile("[0-9]+");
	                	StringTokenizer st= new StringTokenizer(matches.get(0), " ");
	                	while(st.hasMoreTokens()){
	                		String token=st.nextToken();
	                		Log.i("voice","value of token"+token);
	                		m = p.matcher(token);
	                		boolean result=m.find();
	                		Log.i("voice"," value of m.find"+result);
	                	
//	                	Matcher m = p.matcher(matches.get(0));

	                	if (result) {
//	                	    System.out.println(m.group(1));
	                		value=token;
	                		int rem_time = Integer.parseInt(value);
	        				rem_time = rem_time * -1;
	        				cal.add(Calendar.MINUTE, rem_time);
	        				Intent alarmintent = new Intent(getApplicationContext(),
	        						AlarmReceiver.class);
	        				alarmintent.putExtra("title", "Reminder");
	        				alarmintent.putExtra("note", SportsActivity.rd.getDesc());
	        				// HELLO_ID is a static variable that must be initialised at the
	        				// BEGINNING OF CLASS with 1;
	        				Date d = cal.getTime();
	        				 DBAdaptor db = new DBAdaptor(getBaseContext());
	        				db.open();
	        				long id1 = db.insertRemainder("Reminder",SportsActivity.rd.getDesc(),d.getTime());
	        				Log.i(" data insertion"," return value are inserting is"+id1);
	        				 db.close();
	        				// example:protected static int HELLO_ID =1;
	        				PendingIntent sender = PendingIntent
	        						.getBroadcast(getApplicationContext(), HELLO_ID,
	        								alarmintent, PendingIntent.FLAG_UPDATE_CURRENT
	        										| Intent.FILL_IN_DATA);
	        				// VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send
	        				// correct extra's informations to
	        				// AlarmReceiver Class
	        				// Get the AlarmManager service

	        				AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
	        				am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

	        				Context context = getApplicationContext();
	        				CharSequence text = "Reminder set for:"+SportsActivity.rd.getDesc();
	        				int duration = Toast.LENGTH_SHORT;

	        				Toast toast = Toast.makeText(context, text, duration);
	        				toast.show();
	        				addTocal(cal,SportsActivity.rd.getDesc());
	                		
	                	  //  Toast.makeText(CareerCenterDetails.this, token, Toast.LENGTH_SHORT).show();
	                	}
	                	}
	                }
	            })
	            .setNegativeButton("Try Again", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int id) {
	                	dialog.cancel();
	                	startVoiceRecognitionActivity();
//	                     dialog.cancel();
	                }
	            })
	             .setNeutralButton("Keyboard",  new DialogInterface.OnClickListener() {
				
//				String mins;
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					AlertDialog.Builder alert = new AlertDialog.Builder(SportsFinalActivity.this);

					alert.setTitle("NUS Reminder");
					alert.setMessage("When do you want to be reminded?");

					// Set an EditText view to get user input
					final EditText inputName = new EditText(SportsFinalActivity.this);
					alert.setView(inputName);

					alert.setPositiveButton("Set Time", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					value = inputName.getText().toString();
					
//					value=token;
            		int rem_time = Integer.parseInt(value);
    				rem_time = rem_time * -1;
    				cal.add(Calendar.MINUTE, rem_time);
    				Intent alarmintent = new Intent(getApplicationContext(),
    						AlarmReceiver.class);
    				alarmintent.putExtra("title", "Reminder");
    				alarmintent.putExtra("note", SportsActivity.rd.getDesc());
    				// HELLO_ID is a static variable that must be initialised at the
    				// BEGINNING OF CLASS with 1;
    				Date d = cal.getTime();
    				 DBAdaptor db = new DBAdaptor(getBaseContext());
    				db.open();
    				long id1 = db.insertRemainder("Reminder",SportsActivity.rd.getDesc(),d.getTime());
    				Log.i(" data insertion"," return value are inserting is"+id1);
    				 db.close();
    				// example:protected static int HELLO_ID =1;
    				PendingIntent sender = PendingIntent
    						.getBroadcast(getApplicationContext(), HELLO_ID,
    								alarmintent, PendingIntent.FLAG_UPDATE_CURRENT
    										| Intent.FILL_IN_DATA);
    				// VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send
    				// correct extra's informations to
    				// AlarmReceiver Class
    				// Get the AlarmManager service

    				AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    				am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

    				Context context = getApplicationContext();
    				CharSequence text = "Reminder set for:"+SportsActivity.rd.getDesc();
    				int duration = Toast.LENGTH_SHORT;

    				Toast toast = Toast.makeText(context, text, duration);
    				toast.show();
    				
    				addTocal(cal,SportsActivity.rd.getDesc());
					}
					});

					alert.show();

					
					
				}
			});
	     AlertDialog alert = builder.create();
	     alert.show();
//	            wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
//	                    matches));
	        }
	        super.onActivityResult(requestCode, resultCode, data);
	    }
	public boolean checkInternetConnection() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		if (cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isAvailable()
				&& cm.getActiveNetworkInfo().isConnected()) {
			return true;

		} else {
			return false;
		}
	}
	
	public void addTocal(Calendar cal1,String desc){

		String[] projection = new String[] { "_id", "name" };
		Uri calendars = Uri.parse("content://com.android.calendar/calendars");
		     
		String calName; 
		 String calId = null; 
		Cursor managedCursor =
		   managedQuery(calendars, projection,
		   "selected=1", null, null);
		if (managedCursor.moveToFirst()) {
			 
			 int nameColumn = managedCursor.getColumnIndex("name"); 
			 int idColumn = managedCursor.getColumnIndex("_id");
			 do {
			    calName = managedCursor.getString(nameColumn);
			    calId = managedCursor.getString(idColumn);
			 } while (managedCursor.moveToNext());
			}
		
		
		ContentValues event = new ContentValues();
		
		event.put("calendar_id", calId);
		event.put("title", "NUS Sports");
		event.put("description", desc);
		//event.put("eventLocation", "Event Location");
		long startTime = cal1.getTimeInMillis();
		long endTime = cal1.getTimeInMillis()+60*60*1000;
		event.put("dtstart", startTime);
		event.put("dtend", endTime);
		event.put("allDay", 1); 
		event.put("eventStatus", 1);
		event.put("visibility", 0);
	//	event.put("hasAlarm", 1);
		Uri eventsUri = Uri.parse("content://com.android.calendar/events");
		  Uri url = getContentResolver().insert(eventsUri, event);
		
	}
	

}
